package com.starsoft.frame.base.service;

import org.springframework.stereotype.Service;

import com.starsoft.frame.base.bean.BasePrefData;
import com.starsoft.frame.base.bean.BasePreference;
import com.starsoft.frame.base.bean.UserContext;
import com.starsoft.frame.core.service.BaseService;

@Service
public class PreferenceService extends BaseService{
	
	public String getPreference(String prefCode){
		return getPreference(prefCode, null);
	}
	
	public String getPreferenceFromEnv(String prefCode){
		String value = System.getProperty(prefCode);
		if(value==null){
			value = System.getenv(prefCode);
		}
		return value;
	}
	
	public String getPreference(String prefCode, UserContext userContext) {
		String value = getPreferenceFromEnv(prefCode);
		if (value != null) {
			return value;
		}
		
		BasePreference pref = hibernateDao.get(BasePreference.class, prefCode);
		if (pref == null){
			return null;
		}
		String type = pref.getPrefType(), owner = "";
		if ("global".equals(type)) {
			return pref.getDefaultValue();
		} 

		if (userContext == null){
			return null;
		}
		if ("role".equals(type)) {
			owner = userContext.getUser().getRoleId().toString();
		} else if ("user".equals(type)) {
			owner = userContext.getUserId().toString();
		} else if ("acount".equals(type)) {
			owner = userContext.getAcountId().toString();
		}
		BasePrefData pd = new BasePrefData(prefCode, owner);
		pd = hibernateDao.get(BasePrefData.class, pd);
		if (pd != null)
			return pd.getPrefValue();
		return null;
	}
	
	public void saveValue(String prefCode, String prefValue, UserContext user) {
		BasePreference pref = hibernateDao.get(BasePreference.class, prefCode);
		if(pref==null){
			pref = new BasePreference();
			pref.setPrefCode(prefCode);
			pref.setPrefName(prefCode);
			pref.setPrefType("global");
		}
		
		String type = pref.getPrefType(), owner = "";
		if ("global".equals(type)) {
			pref.setDefaultValue(prefValue);
			hibernateDao.saveOrUpdate(pref);
			return;
		}
		
		if ("user".equals(type)) {
			owner = user.getUserId().toString();
		} else if ("role".equals(type)) {
			owner = user.getUser().getRoleId().toString();
		}
		BasePrefData pd = new BasePrefData(prefCode, owner);
		pd.setPrefValue(prefValue);
		hibernateDao.saveOrUpdate(pd);
	}
	
}
